import { bomApi } from '@/api';
import { getDataConfig } from '@/api/data-config';
import { withRedirect } from '@/hocs/withRedirect';
import { IPlank } from '@/types';
import { excludeModel } from '@/utils/model';
import { createReqTip } from '@/utils/promise';
import { PageContainer } from '@ant-design/pro-layout';
import { useModel } from '@umijs/max';
import { useAsyncEffect } from 'ahooks';
import { Button, message } from 'antd';
import { useState } from 'react';
import { DataDiffTable } from './components/DataDiff';

const log = console.log.bind(null, '[page: Diff]');

function IndexPage() {
  const [plankDatas, setPlankDatas] = useState<IPlank[]>([]);
  const [markedDatas, setMarkedDatas] = useState<IPlank[]>([]);
  const {
    design: { designId },
  } = useModel('bom');

  async function fetchPlankData() {
    return await bomApi.getDesignPlanks({ designId });
  }

  async function refreshData() {
    const { excludeModelNames } = await getDataConfig();
    const filterData = (data: IPlank[]) =>
      data.filter((item) => excludeModel(item, excludeModelNames));
    const plankDatas = await fetchPlankData();
    const markedDatas = await bomApi.getMarkedPlankList({
      designId,
    });
    setPlankDatas(filterData(plankDatas));
    setMarkedDatas(filterData(markedDatas));
    log('diff', { designId, markedDatas, plankDatas });
  }

  useAsyncEffect(refreshData, [designId]);

  return (
    <PageContainer>
      <DataDiffTable
        beforeOpen={async () => {
          // await fetchMarkedData();
          // log('diff', { markedDatas, plankDatas });
        }}
        oldPlanks={markedDatas}
        newPlanks={plankDatas}
        onRefresh={refreshData}
        extraBtns={
          <>
            <Button
              type="primary"
              onClick={async () => {
                await refreshData().then(...createReqTip('刷新数据', message));
              }}
            >
              刷新数据
            </Button>
          </>
        }
      />
    </PageContainer>
  );
}

IndexPage.displayName = 'DiffPage';

export default withRedirect(IndexPage, {
  useRedirect() {
    const {
      design: { designId },
    } = useModel('bom');
    if (!designId) {
      return '/home';
    }
    return '';
  },
});
